﻿using Back_end.Models;
using Microsoft.AspNet.Identity.Owin;
using System;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace Back_end.Controllers
{
	/// <summary>
	/// 用户管理
	/// 仅超级管理员和管理员可访问
	/// </summary>
	[Authorize(Roles = "SuperUser, Admin")]
    public class ApplicationUsersController : Controller
    {
        private ApplicationDbContext db = new ApplicationDbContext();
		private ApplicationUserManager _userManager;

		public ApplicationUserManager UserManager
		{
			get
			{
				return _userManager ?? Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
			}
			private set
			{
				_userManager = value;
			}
		}

		public ActionResult Index(string search, string genre)
		{
			var users = from u in db.Users
						where u.Roles.Count == 0
						orderby u.UserName
						select u;

			if (!string.IsNullOrWhiteSpace(search))
			{
				ViewBag.Sub = genre;
				if (genre == "真实姓名")
					return View(users.Where(u => u.RealName.Contains(search)));
				else if (genre == "所在地")
					return View(users.Where(u => u.Location.Contains(search)));
				else
					return View(users.Where(u => u.UserName.Contains(search)));
			}

			ViewBag.Title = search + " - 搜索结果";
			ViewBag.Sub = null;
			return View(users);
		}

        // GET: ApplicationUsers/Details/5
        public ActionResult Details(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            ApplicationUser applicationUser = db.Users.Find(id);
            if (applicationUser == null)
            {
                return HttpNotFound();
            }
            return View(applicationUser);
        }

        // GET: ApplicationUsers/Edit/5
        public ActionResult Edit(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            ApplicationUser applicationUser = db.Users.Find(id);
            if (applicationUser == null)
            {
                return HttpNotFound();
            }
            return View(applicationUser);
        }

        // POST: ApplicationUsers/Edit/5
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
        // 详细信息，请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,AccessFailedCount")] ApplicationUser applicationUser)
        {
            if (ModelState.IsValid)
            {
                db.Entry(applicationUser).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(applicationUser);
        }

		public ActionResult UnLockedDate(string id)
		{
			if (id == null)
				return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
			if (db.Users.Find(id) == null)
				return new HttpStatusCodeResult(HttpStatusCode.NotFound);

			UserManager.SetLockoutEndDateAsync(id, DateTime.UtcNow);
			return RedirectToAction("Edit/" + id);
		}

		public async Task<ActionResult> ComplaintsList(string name)
		{
			if (name == null)
				return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
			var user = await UserManager.FindByNameAsync(name);
			if (user == null)
				return new HttpStatusCodeResult(HttpStatusCode.NotFound);

			ViewBag.UserName = name;
			return View(user.Complaints.ToList());
		}

		//public async Task<ActionResult> FollowedList(string name)
		//{
		//	if (name == null)
		//		return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
		//	var user = await UserManager.FindByNameAsync(name);
		//	if (user == null)
		//		return new HttpStatusCodeResult(HttpStatusCode.NotFound);

		//	ViewBag.UserName = name;
		//	// TODO: 添加列表
		//	return View();

		//	//TempData["list"] = user.Followed.ToList();
		//	//return RedirectToAction("Index", "Complaints", new { list = user.Followed.ToList() });
		//}

		public async Task<ActionResult> LockedAccount(string id, int days)
		{
			if (id == null)
				return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
			var user = await UserManager.FindByNameAsync(id);
			if (user == null)
				return new HttpStatusCodeResult(HttpStatusCode.NotFound);

			user.LockoutEndDateUtc = DateTime.UtcNow.AddDays(days);
			return RedirectToAction("Edit", new { userId = id });
		}

		protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
